﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="recPaymentUpdateform.aspx.cs"
    Inherits="SIPO.Web.Forms.Transaction.recUpdatePaymentform" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Update Payment Form</title>
</head>

<link type="text/css" rel="stylesheet" href="<%= ResolveUrl("~/styles/ui.jqgrid.css") %>" />

<script src="<%= ResolveUrl("~/scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%= ResolveUrl("~/scripts/jquery.validate.wrapper.js") %>" type="text/javascript"></script>

<script type="text/javascript" src="<%= ResolveUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>

<style type="text/css">
    .ui-autocomplete
    {
        max-height: 100px;
        overflow-y: auto; /* prevent horizontal scrollbar */
        overflow-x: hidden; /* add padding to account for vertical scrollbar */
        padding-right: 20px;
    }
    .custom-combobox
    {
        position: relative;
        display: inline-block;
    }
    .custom-combobox-toggle
    {
        position: absolute;
        top: 0;
        bottom: 0;
        margin-left: -1px;
        padding: 0; /* support: IE7 */
        height: 1.7em;
        top: 0.1em;
    }
    .custom-combobox-input
    {
        margin: 0;
        padding: 0.3em;
    }
    .style1
    {
        width: 225px;
    }
    .style2
    {
        width: 111px;
    }
</style>
<script type="text/javascript" language="javascript">

    (function ($) {

        $.widget("custom.combobox", {
            _create: function () {
                this.wrapper = $("<span>")
          .addClass("custom-combobox")
          .insertAfter(this.element);

                this.element.hide();
                this._createAutocomplete();
                this._createShowAllButton();
            },

            _createAutocomplete: function () {
                var selected = this.element.children(":selected"),
          value = selected.val() ? selected.text() : "";

                var width = this.element.width() > 100 ? "style='width:" + this.element.width() + "px';" : "";

                this.input = $("<input " + width + ">")
          .appendTo(this.wrapper)
          .val(value)
          .attr("title", "")
          .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
          .autocomplete({
              autoFocus: true,
              selectFirst: true,
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
          })
          .tooltip({
              tooltipClass: "ui-state-highlight"
          });

                this._on(this.input, {
                    autocompleteselect: function (event, ui) {
                        ui.item.option.selected = true;
                        this._trigger("select", event, {
                            item: ui.item.option
                        });

                        var idOfCaller = this.element.attr('id');
                        switch (idOfCaller.toLowerCase()) {

                            case ("ddlbank"):
                                $('#ddlBank').change();
                                break;
                            default:
                                break;
                        }

                    },

                    autocompletechange: "_removeIfInvalid"
                });
            },

            _createShowAllButton: function () {
                var input = this.input,
          wasOpen = false;

                $("<a>")
          .attr("tabIndex", -1)
          .attr("title", "Tamplikan Semua Item")
          .tooltip()
          .appendTo(this.wrapper)
          .button({
              icons: {
                  primary: "ui-icon-triangle-1-s"
              },
              text: false
          })
          .removeClass("ui-corner-all")
          .addClass("custom-combobox-toggle ui-corner-right")
          .mousedown(function () {
              wasOpen = input.autocomplete("widget").is(":visible");
          })
          .click(function () {
              input.focus();

              // Close if already visible
              if (wasOpen) {
                  return;
              }

              // Pass empty string as value to search for, displaying all results
              input.autocomplete("search", "");
          });
            },

            _source: function (request, response) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response(this.element.children("option").map(function () {
                    var text = $(this).text();
                    if (this.value && (!request.term || matcher.test(text)))
                        return {
                            label: text,
                            value: text,
                            option: this
                        };
                }));
            },

            _removeIfInvalid: function (event, ui) {

                // Selected an item, nothing to do
                if (ui.item) {
                    return;
                }

                // Search for a match (case-insensitive)
                var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
                this.element.children("option").each(function () {
                    if ($(this).text().toLowerCase() === valueLowerCase) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                // Found a match, nothing to do
                if (valid) {
                    return;
                }

                // Remove invalid value
                this.input
          .val("")
          .attr("title", value + " tidak ditemukan")
          .tooltip("open");
                this.element.val("");
                this._delay(function () {
                    this.input.tooltip("close").attr("title", "");
                }, 2500);
                this.input.data("ui-autocomplete").term = "";
            },

            _destroy: function () {
                this.wrapper.remove();
                this.element.show();
            },
            autocomplete: function (value, text) {
                this.element.val(value);
                this.input.val(text);
            }
        });
    })(jQuery);

    $(function () {
        $("#ddlBank").combobox();
    });

</script>
<script type="text/javascript">

    $(document).ready(function () {

        $("#btnSave").button({ icons: { primary: "ui-icon-disk"} });
        $("#btnClose").button({ icons: { primary: "ui-icon-close"} });
        $('#btnClose').click(function () {
            parent.$('#dialog').dialog("close");

            return false;
        });

    });

</script>
<script type="text/javascript">
    $(document).ready(function () {

        // 1. prepare the validation rules and messages.
        var rules = {
            txtTanggalPembayaran: "required"
        };
        var messages = {
            txtTanggalPembayaran: "Tgl. Pembayaran wajib di isi"
        };

        // 2. Initiate the validator
        var validator = new jQueryValidatorWrapper("form1", rules, messages);

        var date = new Date();
        var currentMonth = date.getMonth();
        var currentDate = date.getDate();
        var currentYear = date.getFullYear();

        $("#txtTanggalPembayaran").datepicker({ showWeek: true, showButtonPanel: true,
            changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy', // yearRange: '1990:2030'
            maxDate: new Date(currentYear, currentMonth, currentDate)
        });

        // 3. Set the click event to do the validation
        $("#btnSave").click(function () {

            if (!validator.validate())
                return;

            var grid = $('#table1');
            var selIds = grid.jqGrid('getGridParam', 'selarrrow'),
                selText = [];
            paymentValues = [];
            $.each(selIds, function () {
                // gabungan Invoice | PaymentValue | DebtorSectorID | Nama Perusahaan
                selText.push(grid.jqGrid('getCell', this, 'InvoiceNo') + "|" + grid.jqGrid('getCell', this, 'PaymentValue') + "|" + grid.jqGrid('getCell', this, 'DebtorSectorID') + "|" + grid.jqGrid('getCell', this, 'recDebtorSector.recDebtor.DebtorName'));
                paymentValues.push(grid.jqGrid('getCell', this, 'PaymentValue'));
            });


            for (var i = 0; i < paymentValues.length; i = i + 1) {
                
                if (paymentValues[i] == "") {
                    alert("Data tidak bisa di simpan,periksa kembali nilai jumlah pembayaran !");
                    return false;
                }
            }


            if (selIds.length == 0) {
                //alert('Pilih data yang mau di ubah !');
                alert('Pilih minimal satu record untuk simpan data.');
            }

            else {



                var tglpembayaran = $('#txtTanggalPembayaran').val();
                var bankid = $("#ddlBank option:selected").val();

                var objrecPayment = new Object();
                objrecPayment.PaymentDate = encodeURIComponent(tglpembayaran);

                jsonData = JSON.stringify(objrecPayment);

                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Transaction/recPaymenthandler.ashx") %>';

                CallAjax(handlerUrl, "?method=updatepembayaran&InvoiceNo=" + selText, jsonData);

                parent.$('#dialog').dialog('close');

                setTimeout("parent.$('#table').trigger('reloadGrid');", 3000);

            }


            return false;
        });
    });

</script>
<script type="text/javascript">
  
    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Transaction/recInvoicehandler.ashx") %>';
    
    $('#table1').jqGrid({
        //url: handlerUrl + '?method=getdatabybankid',
        datatype: 'json',
        colNames: ['DebtorSectorID', 'No. Surat Setoran', 'Perusahaan', 'Jumlah Surat setoran (Rp)', 'Jumlah Pembayaran (Rp)'],
        colModel: [
                    { name: 'DebtorSectorID', hidden:true,index: 'DebtorSectorID', width: 200 },
                    { name: 'InvoiceNo', index: 'InvoiceNo', width: 100 },
                    { name: 'recDebtorSector.recDebtor.DebtorName', index: 'DebtorName', width: 200 },
                    { name: 'InvoiceValue', index: 'InvoiceValue', formatter: 'currency', align: 'right', formatoptions: { decimalSeparator: ",", thousandsSeparator: ".", decimalPlaces: 2 }, width: 150 },
                    { name: 'PaymentValue', editable: true, edittype: 'text', index: 'PaymentValue', formatter: 'currency', align: 'right', formatoptions: { decimalSeparator: ",", thousandsSeparator: ".", decimalPlaces: 2 }, width: 150 }
           	],
        rowNum: 10,
        id: 'InvoiceNo',
        multiselect: true,
        rowList: [5, 10, 15, 20],
        pager: '#pager1',
        sortname: 'InvoiceNo',
        sortorder: "asc",
        viewrecords: true,
        jsonReader: { repeatitems: false },
        width: 800,
        cellEdit: true,
        cellsubmit:'clientArray',
        height: '100%',
        caption: 'Pembayaran',
        ajaxGridOptions: { cache: false }
    });

            

    $("#table1").jqGrid('navGrid', '#pager1', { edit: false, add: false, del: false, searchtext: 'Search', refreshtext: 'Refresh' },
        {}, {}, {}, { closeOnEscape: true, multipleSearch: true, closeAfterSearch: true });     
</script>
<script language="javascript" type="text/javascript">

    $(document).ready(function () {
        getBankAccount();
       
        $('#ddlBank').change(function () {
            refreshGrid($(this).val());
        });

    });

    function refreshGrid(bankID) {
        
       setTimeout("$('#table1').trigger('reloadGrid');", 2000);
        $("#table1").jqGrid('setGridParam', { url: handlerUrl + '?method=getdatabybankid&bankID=' + bankID }).trigger('reloadGrid');

    }

    function getBankAccount() {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getbankaccount.ashx") %>';

        $ddlBank = $('#ddlBank');
        $('#ddlBank').find('option:not(:first)').remove();
        $.ajax({
            type: 'POST',
            url: handlerUrl,
            contentType: 'application/json',
            dataType: 'json',
            success: function (datas) {

                if (datas.length > 1) {

                    $ddlBank.get(0).options[0] = new Option("-- pilih bank --", "");
                    $.each(datas, function (i, data) {
                        $ddlBank.append('<option value="' + data.BankID + '">' + data.BankCode + ' - ' + data.BankName + '</option>');
                    });
                    $ddlBank.combobox('autocomplete', "", "-- pilih bank --");
                }
                else {
                    if (datas.length == 1) {
                        $ddlBank.append('<option value="' + datas[0].BankID + '">' + datas[0].BankCode + ' - ' + datas[0].BankName + '</option>');
                        $ddlBank.combobox('autocomplete', datas[0].BankID, datas[0].BankCode + ' - ' + datas[0].BankName);

                        refreshGrid(datas[0].BankID);
                    }
                    else {
                        $ddlBank.get(0).options[0] = new Option("-- tidak ada data --", "");
                        $ddlBank.combobox('autocomplete', "", "-- tidak ada data --");
                    }
                }
            },
            error: function () {
                alert('Error load data bank !');
            }
        });

    }
</script>
<body>
    <form id="form1" runat="server">
    <table border="0">
        <tr>
            <td style="width: 50">
                Bank
            </td>
            <td>
                :
            </td>
            <td>
                <asp:DropDownList ID="ddlBank" runat="server" Width="300">
                </asp:DropDownList>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: Red;">*</span>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td style="width: 50">
                Tgl. Pembayaran
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtTanggalPembayaran" runat="server" Width="100" MaxLength="10"></asp:TextBox>&nbsp;
                <span style="color: Red;">*</span>
            </td>
        </tr>
    </table>
    <br />
    <div>
        <table id="table1" class="scroll" cellpadding="0" cellspacing="0">
        </table>
        <div id="pager1" class="scroll">
        </div>
    </div>
    <br />
    <div style="text-align: right; padding-top: 10px;">
        <button id="btnSave" type="button">
            Simpan</button>
        <button id="btnClose" type="button">
            Batal</button>
    </div>
    </form>
</body>
</html>
